package com.ckjava.test.web;

import com.alibaba.fastjson.JSONObject;
import com.ckjava.test.domain.PageParamer;
import com.ckjava.test.domain.Task;
import com.ckjava.test.service.TaskService;
import com.ckjava.test.web.base.BaseJpaCrudController;
import com.ckjava.xutils.ExceptionUtils;
import com.ckjava.xutils.http.HttpResponse;
import com.ckjava.xutils.http.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Api
@RestController
@RequestMapping(value = "/api/task", produces = "application/json;charset=utf-8")
public class TaskController extends BaseJpaCrudController<TaskService, Task> {

    @ApiOperation("分页获取数据")
    @GetMapping(value = "page")
    public HttpResponse<Page<Task>> page(
            @ApiParam("{\n" +
                    "    \"sort\": {\n" +
                    "        \"predicate\": \"id\",\n" +
                    "        \"reverse\": true\n" +
                    "    },\n" +
                    "    \"search\": {\n" +
                    "        \"predicateObject\": {\n" +
                    "            \"name\": \"like,test\"\n" +
                    "        }\n" +
                    "    },\n" +
                    "    \"pagination\": {\n" +
                    "        \"start\": 1,\n" +
                    "        \"totalItemCount\": 0,\n" +
                    "        \"number\": 10,\n" +
                    "        \"numberOfPages\": 2\n" +
                    "    }" +
                    " }\n" +
                    "对于 predicateObject 中的参数，如果 activity=false, 传参为： \"activity\": \"=,false\"，" +
                    "如果 activity like '%false%', 传参为 \"activity\": \"like,false\"" +
                    "}")
            @RequestParam String params) {
        try {

            PageParamer pageParamer = JSONObject.parseObject(params, PageParamer.class);

            Task task = new Task();

            // 排序
            task.setOrderBy(pageParamer.getSort().getPredicate());
            task.setDesc(pageParamer.getSort().isReverse());

            // 查询字段
            task.setConditionMap(pageParamer.getSearch().getPredicateObject());

            // 分页导航
            task.setStart(pageParamer.getPagination().getStart());
            task.setPageSize(pageParamer.getPagination().getNumber());

            Page<Task> page = service.getPage(task);
            return HttpResponse.getReturn(page, HTTPCODE.code_200, null);
        } catch (Exception e) {
            return HttpResponse.getReturn(null, HTTPCODE.code_500, ExceptionUtils.getExceptionMsg(e));
        }

    }
}
